package fragments;

import java.util.List;

import adapters.ChooseAlbumAdapter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import com.yandex.yandexfotki.R;
import com.yandex.yandexfotki.activities.StartActivity;

import entities.Album;

public class AddOptionsFragment extends Fragment{

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		List<Album> t = ((StartActivity)getActivity()).getYapi().getAlbumsList();
		selectedAlbum = t.get(0);
		chAlbum.setAdapter(new ChooseAlbumAdapter((StartActivity)getActivity(), t));
		chAlbum.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				selectedAlbum = ((StartActivity)getActivity()).getYapi().getAlbumsList().get(arg2);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.addoptions, container,false);
		initViews(v);
		return v;
	}
	
	private void initViews(View v) {
		chAlbum = (Spinner) v.findViewById(R.id.choosealbum);
		title = (EditText)v.findViewById(R.id.title);
		description = (EditText)v.findViewById(R.id.description);
		
		Button submit = (Button)v.findViewById(R.id.submit);
		submit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				submit();
			}
		});
		
		Button addAlbum = (Button)v.findViewById(R.id.addalbum);
		addAlbum.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				((StartActivity)getActivity()).startCreateAlbumFragment();
			}
		});
	}
	
	private void submit() {
		 String titleValue = title.getText().toString();
		 String descriptionValue = description.getText().toString();
		 PreviewPhotoFragment pvf = (PreviewPhotoFragment)getActivity().getSupportFragmentManager().findFragmentByTag("preview");
		 pvf.setOptions(selectedAlbum, titleValue, descriptionValue);
		 getFragmentManager().popBackStack();
	}
	
	public void addNewAlbum(Album al) {
//		((ChooseAlbumAdapter)chAlbum.getAdapter()).addAlbum(al);
		((StartActivity)getActivity()).getYapi().addAlbum(al);
	}
	
	EditText title;
	EditText description;
	Spinner chAlbum;
	Album selectedAlbum;
}
